﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : System.Web.UI.Page
{
    // For generating random numbers.
    private Random random = new Random();
    public DBDataContext db = new DBDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBoxUserName.Attributes.Add("onfocus", "clearText(this);");
            TextBoxUserName.Attributes.Add("onblur", "clearText(this);");
            TextBoxPassword.Attributes.Add("onfocus", "clearText(this);");
            TextBoxPassword.Attributes.Add("onblur", "clearText(this);");
            TextBoxCodeNumber.Attributes.Add("onfocus", "clearText(this);");
            TextBoxCodeNumber.Attributes.Add("onblur", "clearText(this);");

            if (Request["error"] != null)
            {
                Message1.Message = Request["error"].ToString();
                Message1.Type = Constant.MESSAGE_ERROR;
            }
            if (Request["msj"] != null)
            {
                Message1.Message = Request["msj"].ToString();
                Message1.Type = Constant.MESSAGE_OK;
            }
            if (Request["LogOut"] != null)
            {
                //Message1.Message = "Usted a salido del sistema";
                //Message1.Type = Constant.MESSAGE_OK;
                Session.RemoveAll();
            }
            RefreshImageCodeNumber();
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButtonUpdate_Click(object sender, EventArgs e)
    {
        RefreshImageCodeNumber();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButtonLogin_Click(object sender, EventArgs e)
    {
        if (this.TextBoxCodeNumber.Text == HiddenFieldCodeNumber.Value)
        {
            int intentsFail = (Session["IntentsFail" + TextBoxUserName.Text] != null) ? int.Parse(Session["IntentsFail" + TextBoxUserName.Text].ToString()) : 0;
            if (intentsFail < 3)
            {
                bool Authenticated = false;
                Authenticated = UserAuthenticate(TextBoxUserName.Text, TextBoxPassword.Text);
                if (Authenticated == true)
                {
                    if (CheckBoxRemember.Checked == true)
                    {
                        Response.Cookies["RFriend_Email"].Value = TextBoxUserName.Text;
                        Response.Cookies["RFriend_PWD"].Value = TextBoxPassword.Text;
                        Response.Cookies["RFriend_Email"].Expires = DateTime.Now.AddMonths(3);
                        Response.Cookies["RFriend_PWD"].Expires = DateTime.Now.AddMonths(3);
                        Response.Cookies["RFriend_UID"].Expires = DateTime.Now.AddMonths(3);
                    }
                    Response.Redirect("Home.aspx");
                }
                else
                {
                    intentsFail++;
                    Message1.Message = "Su intento de inicio de sesión no se realizó correctamente. Por favor, inténtelo de nuevo.";
                    Session["IntentsFail" + TextBoxUserName.Text] = intentsFail;
                }
            }
            else
            {
                Message1.Message = "Ha superado el número máximo de intentos de acceso, intentelo luego de 10 minutos.";
                Message1.Type = Constant.MESSAGE_ERROR;
            }
        }
        else
        {
            // Display an informational message.
            Message1.Message = "Código de seguridad incorrecto, inténtelo nuevamente.";
            Message1.Type = Constant.MESSAGE_ERROR;

            // Clear the input and create a new random code.
            this.TextBoxUserName.Text = "";
        }
        RefreshImageCodeNumber();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinkButtonRememberPassword_Click(Object sender, EventArgs e)
    {
        if (db.UserQs.Any(u => u.Email.Equals(TextBoxUserName.Text)))
        {
            UserQ user = db.UserQs.First(u => u.Email.Equals(TextBoxUserName.Text));
            bool valid = false;
            try
            {
                SendMail.RememberPassword(user.Email, user.Password);
                valid = true;
            }
            catch (Exception ex)
            {
                Message1.Message = "Inténtelo nuevamente.";
                Message1.Type = Constant.MESSAGE_ERROR;
            }
            if (valid)
            {
                Message1.Message = "El mensaje fue enviado a su cuenta de correo.";
                Message1.Type = Constant.MESSAGE_ERROR;
            }
        }
        else
        {
            Message1.Message = "Inténtelo nuevamente.";
            Message1.Type = Constant.MESSAGE_ERROR;
        }
        RefreshImageCodeNumber();
    }

    /// <summary>
    /// 
    /// </summary>
    public void RefreshImageCodeNumber()
    {
        string codeNumber = GenerateRandomCode();
        TextBoxCodeNumber.Text = "Código de imagen";
        HiddenFieldCodeNumber.Value = codeNumber;
        ImgCaptcha.Src = "JpegImage.aspx?code=" + codeNumber;
        ImgCaptcha.ViewStateMode = System.Web.UI.ViewStateMode.Disabled;

    }

    /// <summary>
    /// Returns a string of six random digits.
    /// </summary>
    /// <returns></returns>
    private string GenerateRandomCode()
    {
        string s = "";
        for (int i = 0; i < 6; i++)
            s = String.Concat(s, this.random.Next(10).ToString());
        return s;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="UserName"></param>
    /// <param name="Password"></param>
    /// <returns></returns>
    private bool UserAuthenticate(string UserName, string Password)
    {
        bool boolReturnValue = false;

        if (db.UserQs.Any(u => u.Email.Equals(UserName) && u.Password.Equals(Password)))
        {
            var userVar = from u in db.UserQs
                          where u.Email.Equals(UserName)
                          where u.Password.Equals(Password)
                          select new { u.Id, u.RoleId };

            UserQ user = null;

            foreach (var u in userVar)
            {
                user = new UserQ();
                user.Id = u.Id;
                user.RoleId = u.RoleId;
            }

            if (user != null)
            {
                if (user.RoleId == -1)
                {
                    boolReturnValue = false;
                    Message1.Message = "El usuario aun no ha sido dado de Alta. Por favor espera la llamada de nuestros asesores para confirmar sus datos. Gracias.";
                    Message1.Type = Constant.MESSAGE_ERROR;
                }
                else
                {
                    boolReturnValue = true;
                    Session["User" + Session.SessionID] = db.UserQs.First(us => us.Id.Equals(user.Id));
                    user.LastLogin = System.DateTime.Now;
                    db.SubmitChanges();
                }
            }
            else
            {
                if (db.UserQs.Any(u => u.Email.Equals(UserName) && u.Password.Equals(Password) && u.RoleId != 5 && u.RoleId != -1))
                {
                    user = db.UserQs.First(u => u.Email.Equals(UserName) && u.Password.Equals(Password) && u.RoleId != 5 && u.RoleId != -1);
                    boolReturnValue = true;
                    Session["User" + Session.SessionID] = user;
                    user.LastLogin = System.DateTime.Now;
                    db.SubmitChanges();
                }
                else
                {
                    boolReturnValue = false;
                    Message1.Message = "El usuario no existe.";
                    Message1.Type = Constant.MESSAGE_ERROR;
                }
            }

        }
        return boolReturnValue;

    }

}